package com.example.messaging;

import java.io.IOException;
import java.io.StringReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.graphics.Bitmap;
import android.util.Log;

import com.example.bitmap.Codec;
import com.example.logging.Logger;
import com.example.networking.Session;

public class GUIInitSMessage extends Message {

	private Bitmap renderedComponent;
//	private String renderedComponentXml;
	private Session session;
	private String renderedComponentFormat;

	public GUIInitSMessage() {
	}

	public void setRenderedComponent(Bitmap renderedComponent) {
		this.renderedComponent = renderedComponent;
	}

	public void setSession(Session session) {
		this.session = session;
	}
	
	public void setRenderedComponentFormat(String renderedComponentFormat) {
		this.renderedComponentFormat = renderedComponentFormat;
	}

	public Bitmap getRenderedComponent() {
		return renderedComponent;
	}

	public Session getSession() {
		return session;
	}

	@Override
	public void setXML() {
		throw new RuntimeException(
				"Unable to call setXML on server message on client side!");
	}

	@Override
	public void decodeXML(String xml) {
		// parse given xml file and fill response with parsed data
		try {

			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			XmlPullParser xpp = factory.newPullParser();

			xpp.setInput(new StringReader(xml));
			int eventType = xpp.getEventType();
			String currentTag = null;
			
			while (eventType != XmlPullParser.END_DOCUMENT) {

				switch (eventType) {
				case XmlPullParser.START_DOCUMENT:
					// TODO possible to remove
					break;
				case XmlPullParser.END_DOCUMENT:
					// TODO possible to remove
					break;
				case XmlPullParser.START_TAG:

					currentTag = xpp.getName();

					if (currentTag.equals("session")) {
						if (xpp.getAttributeName(0).equals("id")) {
							setSession(new Session(xpp.getAttributeValue(0)));
						}
						break;
					}
					
					if (currentTag.equals("image")) {
						if (xpp.getAttributeName(0).equals("format")) {
							setRenderedComponentFormat(xpp.getAttributeValue(0));
						}
						
						xpp.next();
						
						// get encoded bitmap
						String base64 = xpp.getText();
						// decode bitmap
						setRenderedComponent(Codec.decodeBase64(base64));
						
						break;
					}

					break;

				case XmlPullParser.END_TAG:

					break;
				case XmlPullParser.TEXT:
					break;
				}

				eventType = xpp.next();
			}

		} catch (XmlPullParserException e) {
			Log.e(Logger.ERR, "XmlPullParserException in XMLHandler");
			e.printStackTrace();
		} catch (IOException e) {
			Log.e(Logger.ERR, "IOException in XMLHandler");
			e.printStackTrace();
		}
	}
}
